﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace EuroAudit
{
    public partial class OrgAdmin : System.Web.UI.Page
    {
        GlobalF GFunc = new GlobalF();

        protected void Page_Load(object sender, EventArgs e)
        {

            if (string.IsNullOrEmpty(Session["UserName"].ToString()) | Session["UserName"].ToString()=="guest")
            {
                Response.Redirect("Login.aspx", true);
                //return;
            }
            if (Session["IsAdmin"].ToString() == "1")
            {
                cmdNew.Visible = true;
                //cmdNewU.Visible = true;
            }
            else
            {
                //return;
            }
            if (IsPostBack)
            {
                if (_RESULT.Text == "OKcmdDel")
                {
                    cmdDelU_Click(sender, e);
                    _RESULT.Text = "";
                }
            }
            AddFilters();
            LoadOrg("");

        }

        void AddFilters()
        {
            Button cmdFilter = new Button();
            cmdFilter.Text = "Visi";
            cmdFilter.Click += new EventHandler(cmdFilter_Click);
            cmdFilter.CssClass = "cmdFilters";
            pFilters.Controls.Add(cmdFilter);
            for (int i = 0; i < 10; i++)
            {
                cmdFilter = new Button();
                cmdFilter.Text = i.ToString();
                cmdFilter.Click += new EventHandler(cmdFilter_Click);
                cmdFilter.CssClass = "cmdFilters";
                pFilters.Controls.Add(cmdFilter);
            }
            pFilters.Controls.Add(new LiteralControl("<br>"));
            for (int i = 65; i < 91; i++)
            {
                cmdFilter = new Button();
                char charF = (char)i;
                cmdFilter.Text = charF.ToString();
                cmdFilter.Click += new EventHandler(cmdFilter_Click);
                cmdFilter.CssClass = "cmdFilters";
                pFilters.Controls.Add(cmdFilter);
            }
        }

        void cmdFilter_Click(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            Button b = (Button)sender;
            if (b.Text == "Visi")
            {
                LoadOrg("");
            }
            else
            {
                LoadOrg(b.Text);
            }
        }

        void LoadOrg(string Filter)
        {
            DataSet dsList;
            //DataSet dsGroupList;
            TableHeaderCell thcNewCell;
            TableHeaderRow thrNewRow;
            TableCell tcNewCell;
            TableRow trNewRow;
            Button cmdEdit;
            string QStr = "";
            /*string LastStruct = "";
            string CurrStruct = "";
            string LastNod = "";
            string CurrNod = "";
            */
            //Button cmdGEdit;
            //string UsersInGroup;

            tOrg.Rows.Clear();
            //
            if (Filter == string.Empty)
            {
                QStr = "SELECT OrgID, OrgName, RegNr, Address, Phone, Email, CPerson, AccessU, AccessG FROM org WHERE RecStatus=0 AND (AccessU LIKE '%;guest;%' OR AccessG LIKE '%;Everyone;%' OR AccessG LIKE '%;Guests;%' OR AccessG LIKE '%;Authenticated users;%' " + Session["WhereGroups"] + ") ORDER BY OrgName";
            }
            else
            {
                QStr = "SELECT OrgID, OrgName, RegNr, Address, Phone, Email, CPerson, AccessU, AccessG FROM org WHERE RecStatus=0 AND OrgName LIKE '" + Filter + "%' AND (AccessU LIKE '%;guest;%' OR AccessG LIKE '%;Everyone;%' OR AccessG LIKE '%;Guests;%' OR AccessG LIKE '%;Authenticated users;%' " + Session["WhereGroups"] + ") ORDER BY OrgName";
            }
            dsList = GFunc.GetData(QStr, "WebCNS", false);
            if (dsList.Tables.Count > 0)
            {
                if (dsList.Tables[0].Rows.Count > 0)
                {
                    thrNewRow = new TableHeaderRow();
                    if (Session["IsAdmin"].ToString() == "1")
                    {
                        thcNewCell = new TableHeaderCell();
                        thcNewCell.Text = "Labot";
                        thrNewRow.Cells.Add(thcNewCell);
                    }
                    foreach (DataColumn Col in dsList.Tables[0].Columns)
                    {
                        thcNewCell = new TableHeaderCell();
                        thcNewCell.Text = Col.ColumnName;
                        thrNewRow.Cells.Add(thcNewCell);
                    }
                    tOrg.Rows.AddAt(0, thrNewRow);

                    //CurrStruct = row["Strukturvieniba"].ToString();
                    //CurrNod = row["Nodala"].ToString();

                    foreach (DataRow row in dsList.Tables[0].Rows)
                    {
                        trNewRow = new TableRow();
                        tcNewCell = new TableCell();
                        if (Session["IsAdmin"].ToString() == "1")
                        {
                            cmdEdit = new Button();
                            cmdEdit.ID = "OrgEdit" + row["OrgID"].ToString();
                            cmdEdit.Text = "Labot";
                            cmdEdit.CssClass = "cmdEdit";
                            cmdEdit.CommandArgument = row["OrgID"].ToString();
                            cmdEdit.PostBackUrl = "#pEdit";
                            cmdEdit.Click += new EventHandler(cmdEdit_Click);
                            tcNewCell.Controls.Add(cmdEdit);
                            Label BkmListG = new Label();
                            BkmListG.Text = "<a name=\"" + row["OrgID"].ToString() + "\"></a>";
                            //BkmListG.Visible = false;
                            tcNewCell.Controls.Add(BkmListG);
                        }
                        trNewRow.Cells.Add(tcNewCell);
                        foreach (DataColumn Col in dsList.Tables[0].Columns)
                        {
                            tcNewCell = new TableCell();
                            if (Col.ColumnName == "OrgName")
                            {
                                tcNewCell.Text = "<a href=DocList.aspx?ViewID=2&NodePath=000/000/"+row["OrgID"].ToString()+"&NodeText="+row[Col].ToString()+"> " + row[Col].ToString() + "</a>";
                            }
                            else
                            {
                                tcNewCell.Text = row[Col].ToString() + "";
                            }
                            trNewRow.Cells.Add(tcNewCell);
                        }
                        tOrg.Rows.Add(trNewRow);

                    }
                }
            }
        }

        void cmdEdit_Click(object sender, EventArgs e)
        {
            string Rec2Edit;
            string QString;
            DataSet ds;
            gvAccessG.DataSource = GFunc.GetData("SELECT GroupName, Description FROM groups WHERE RecStatus=0 ORDER BY GroupName", "WebCNS", false);
            gvAccessG.DataBind();
            gvAccessG.Visible = false;
            //dsUsers.ConnectionString = GFunc.GetConnectionString("WebCNS");
            gvAccessU.DataSource = GFunc.GetData("SELECT User, LongName, Groups FROM users WHERE RecStatus=0 ORDER BY User", "WebCNS", false);
            gvAccessU.DataBind();
            gvAccessU.Visible = false;

            System.Web.UI.WebControls.Button b = sender as System.Web.UI.WebControls.Button;
            Rec2Edit = b.ID.Substring(7);
            QString = "SELECT * FROM org WHERE RecStatus=0 AND OrgID='" + Rec2Edit + "'";
            ds = GFunc.GetData(QString, "WebCNS", false);
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    DataRow row = ds.Tables[0].Rows[0];
                    txtOrgID.Text = row["OrgID"].ToString();
                    txtOrgName.Text = row["OrgName"].ToString();
                    txtRegNr.Text = row["RegNr"].ToString();
                    txtAddress.Text = row["Address"].ToString();
                    txtPhone.Text = row["Phone"].ToString();
                    txtEmail.Text = row["Email"].ToString();
                    txtCPerson.Text = row["CPerson"].ToString();
                    txtAccessU.Text = row["AccessU"].ToString();
                    txtAccessG.Text = row["AccessG"].ToString();
                }
            }
            cmdCloseU.PostBackUrl = "#" + b.CommandArgument;
            pEdit.Visible = true;

        }

        protected void cmdNew_Click(object sender, EventArgs e)
        {
            //dsGroups.ConnectionString = GFunc.GetConnectionString("WebCNS");
            gvAccessG.DataSource = GFunc.GetData("SELECT GroupName, Description FROM groups WHERE RecStatus=0 ORDER BY GroupName", "WebCNS", false);
            gvAccessG.DataBind();
            gvAccessG.Visible = false;
            //dsUsers.ConnectionString = GFunc.GetConnectionString("WebCNS");
            gvAccessU.DataSource = GFunc.GetData("SELECT User, LongName, Groups FROM users WHERE RecStatus=0 ORDER BY User", "WebCNS", false);
            gvAccessU.DataBind();
            gvAccessU.Visible = false;

            txtOrgID.Text = "";
            txtOrgName.Text = "";
            txtRegNr.Text = "";
            txtAddress.Text = "";
            txtPhone.Text = "";
            txtEmail.Text = "";
            txtCPerson.Text = "";
            txtAccessU.Text = "";
            txtAccessG.Text = "";


            pEdit.Visible = true;

        }

        protected void cmdCloseU_Click(object sender, EventArgs e)
        {
            lblErr.Text = "";
            pEdit.Visible = false;

        }

        protected void cmdDelU_Click(object sender, EventArgs e)
        {
            string StrDel;

            lblErr.Text = "";
            StrDel = "UPDATE org SET RecStatus=1 WHERE OrgID='" + txtOrgID.Text + "'";
            GFunc.GetData(StrDel, "WebCNS", false);
            lblErr.Text = "Saraksta dati ir izdzēsti.";
        }


        protected void cmdSave_Click(object sender, EventArgs e)
        {
            string[] c = new string[12];
            string QString = "";
            string LastID = "";
            DataSet dsLastID;

            lblErr.Text = "";

            if (txtOrgName.Text.Length == 0)
            {
                lblErr.Text = "Nav norādīts organizācijas nosaukums!";
                return;
            }
            if (txtRegNr.Text.Length == 0)
            {
                lblErr.Text = "Nav norādīts reģistrācijas Nr!";
                return;
            }
            try
            {
                c[0] = "OrgID='" + GFunc.EscapeSQLCahrs(txtOrgID.Text) + "'";
                c[1] = "OrgName='" + GFunc.EscapeSQLCahrs(txtOrgName.Text) + "'";
                c[2] = "RegNr='" + GFunc.EscapeSQLCahrs(txtRegNr.Text) + "'";
                c[3] = "Address='" + GFunc.EscapeSQLCahrs(txtAddress.Text) + "'";
                c[4] = "Phone='" + GFunc.EscapeSQLCahrs(txtPhone.Text) + "'";
                c[5] = "Email='" + GFunc.EscapeSQLCahrs(txtEmail.Text) + "'";
                c[6] = "CPerson='" + GFunc.EscapeSQLCahrs(txtCPerson.Text) + "'";
                c[7] = "AccessU='" + GFunc.EscapeSQLCahrs(txtAccessU.Text) + "'";
                c[8] = "AccessG='" + GFunc.EscapeSQLCahrs(txtAccessG.Text) + "'";
                c[9] = "UserEdit='" + GFunc.EscapeSQLCahrs(Session["UserName"].ToString()) + "'";
                c[10] = "UserAdd='" + GFunc.EscapeSQLCahrs(Session["UserName"].ToString()) + "'";
                c[11] = "TimeAdd='" + GFunc.EscapeSQLCahrs(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) + "'";
                if (txtOrgID.Text.Length != 0)
                {
                    QString = "UPDATE org SET " + c[1] + "," + c[2] + "," + c[3] + "," + c[4] + "," + c[5] + "," + c[6] + "," + c[7] + "," + c[8] + "," + c[9] + " WHERE " + c[0];
                }
                else
                {
                    QString = "INSERT INTO org SET " + c[1] + "," + c[2] + "," + c[3] + "," + c[4] + "," + c[5] + "," + c[6] + "," + c[7] + "," + c[8] + "," + c[9] + "," + c[10] + "," + c[11];
                }
                dsLastID = GFunc.GetData(QString, "WebCNS", true);
                if (txtOrgID.Text.Length == 0)
                {

                    if (dsLastID.Tables.Count > 0)
                    {
                        if (dsLastID.Tables["tLID"].Rows.Count > 0)
                        {
                            txtOrgID.Text = dsLastID.Tables["tLID"].Rows[0]["LID"].ToString();
                        }
                    }
                }
                lblErr.Text = "Klienta dati ir saglabāti.";
            }
            catch (Exception ex)
            {
                lblErr.Text = ex.Message;
            }
        }

        protected void cmdShowU_Click(object sender, EventArgs e)
        {
            gvAccessU.Visible = !gvAccessU.Visible;
        }

        protected void cmdShowG_Click(object sender, EventArgs e)
        {
            gvAccessG.Visible = !gvAccessG.Visible;
        }

        protected void gvAccessU_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (txtAccessU.Text.Contains(";" + gvAccessU.SelectedRow.Cells[1].Text + ";"))
            {
                txtAccessU.Text = txtAccessU.Text.Replace(";" + gvAccessU.SelectedRow.Cells[1].Text + ";", ";");
            }
            else
            {
                txtAccessU.Text = txtAccessU.Text + ";" + gvAccessU.SelectedRow.Cells[1].Text + ";";
                txtAccessU.Text = txtAccessU.Text.Replace(";;", ";");
            }
        }

        protected void gvAccessG_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (txtAccessG.Text.Contains(";" + gvAccessG.SelectedRow.Cells[1].Text + ";"))
            {
                txtAccessG.Text = txtAccessG.Text.Replace(";" + gvAccessG.SelectedRow.Cells[1].Text + ";", ";");
            }
            else
            {
                txtAccessG.Text = txtAccessG.Text + ";" + gvAccessG.SelectedRow.Cells[1].Text + ";";
                txtAccessG.Text = txtAccessG.Text.Replace(";;", ";");
            }
        }


    }
}
